package team.first.movieapiv2pro.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.mongodb.DBObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import team.first.movieapiv2pro.dao.RegionDAO;
import team.first.movieapiv2pro.domain.Region;
import team.first.movieapiv2pro.service.RegionService;

import java.time.Duration;
import java.util.List;

/**
 * @Author: HAPPY
 * @Project_name: project
 * @Package_name: team.first.movieapiv2pro.service.impl
 * @Date: 2021/12/26 10:16
 * @Description:
 */
@Service
public class RegionServiceImpl implements RegionService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    RegionDAO regionDAO;

    @Override
    public List<Region> list() {
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String regions = operations.get("movie-api-v2:data:regions");

        List<Region> regionList;

        if (regions != null) {
            regionList = JSON.parseArray(regions, Region.class);
        } else {
            List<DBObject> dbObjects = regionDAO.selectAll();
            regionList = BeanUtil.copyToList(dbObjects, Region.class);
            // 对结果进行缓存, 因为不会怎么变，所以设置60分钟
            stringRedisTemplate.opsForValue().set("movie-api-v2:data:regions", JSON.toJSONString(regionList), Duration.ofSeconds(60 * 60));
        }
        return regionList;
    }
}
